package cn.anecansaitin.firecrafting.common.event;

import cn.anecansaitin.firecrafting.ModConstant;
import cn.anecansaitin.firecrafting.common.block.ModBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.Explosion;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.AABB;
import net.minecraftforge.event.world.ExplosionEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

import java.util.List;
import java.util.Random;

@Mod.EventBusSubscriber(modid = ModConstant.MOD_ID)
public class EndCrystalExplosionEvent {
    private static final Random random = new Random();

    @SubscribeEvent
    public static void explosion(ExplosionEvent.Detonate event) {
        Level world = event.getWorld();
        if (world.isClientSide()) {
            return;
        }
        //获取爆炸
        Explosion explosion = event.getExplosion();

        if (world.dimensionType().effectsLocation() == DimensionType.END_EFFECTS) {
            BlockPos pos = new BlockPos(explosion.getPosition());
            List<Entity> list = world.getEntities((Entity) null, new AABB(pos.getX() - 1, pos.getY() - 1, pos.getZ() - 1, pos.getX() + 2, pos.getY() + 2, pos.getZ() + 2), (e) -> {
                EntityType<?> type = e.getType();
                return type == EntityType.END_CRYSTAL;
            });

            for (Entity entity : list) {
                if (random.nextFloat() < 0.1) {
                    BlockPos onPos = entity.getOnPos().above();
                    world.setBlockAndUpdate(onPos, ModBlocks.ENDER_FIRE.get().defaultBlockState());
                    event.getAffectedBlocks().remove(onPos);
                }
            }
        }
    }
}
